import { defineStore } from 'pinia';
import { reqCode, reqUserLogin } from '@/api/hospital';
import type { LoginData, UserLoginResponseData } from '@/api/hospital/type';
// 引入详情的ts类型
import type { UserState } from './interface/index';
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "@/utils/user";

const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      visiable: false, // 用于控制登录组件的dialog显示与隐藏
      code: '',
      userInfo: JSON.parse(GET_TOKEN() as string) || {}
    }
  },
  actions: {
    // 获取验证码
    async getCode(phone: string) {
      let res: any = await reqCode(phone)
      if (res.code == 200) {
        this.code = res.data
        return 'ok';
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
    // 用户登录
    async login(data: LoginData) {
      let res: UserLoginResponseData = await reqUserLogin(data)
      if (res.code == 200) {
        this.userInfo = res.data
        SET_TOKEN(JSON.stringify(this.userInfo));
        return 'ok';
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
    //退出登录方法
    logout() {
      //清空仓库的数据
      this.userInfo = { name: '', token: '' };
      //清空本地存储的数据
      REMOVE_TOKEN();
    },
    // 查询微信扫码的接口（看本地存储是否存储数据）
    queryState() {
      //开启定时器每隔一段时间问:本地存储是否拥有用户信息
      let timer = setInterval(() => {
        if (GET_TOKEN()) {
          this.visiable = false
          this.userInfo = JSON.parse(GET_TOKEN() as string)
          clearInterval(timer)
        }
      }, 1000)
    }
  },
  getters: {

  }
})

export default useUserStore;